#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , u_homepage(nullptr)
    ,u_userpage(nullptr)
    ,u_stallpage(nullptr)
    ,u_carpage(nullptr)
    ,u_accespage(nullptr)
{
    ui->setupUi(this);
    sqlite_init();

    page_init();

    this->setWindowTitle("智慧泊车系统");
    this->setWindowIcon(QIcon(":/picture/BMW.ico"));

    socket_data = new QTcpSocket;
    socket_send_data = new QTcpSocket;
    get_car_num = new Carnum(image);
    get_car_num->run();
    flag = 0;
    connect(socket_data, SIGNAL(readyRead()), this, SLOT(get_datas()));

    connect(get_car_num, &Carnum::numDataReceived, this, &Widget::Car_Num);

    connect(u_stallpage,&stallpage::sendMsg,this,&Widget::sentMsg);
    connect(u_stallpage,&stallpage::parking_fee,this,&Widget::sentMsg);

    connect(get_car_num, &Carnum::picDataReceived, this, &Widget::get_image);
}

Widget::~Widget()
{
    delete ui;
}

//ParkingLot--数据库初始化
void Widget::sqlite_init()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //创建数据库连接
    db.setDatabaseName("D:../ParkingLot.db");    //设置连接数据库名称
    db.open();                          //打开数据库
    if(!db.isOpen()){
        qDebug() << "数据库连接失败" ;
    }else{
        qDebug() << "数据库已打开！";
    }

}

void Widget::recvMsg(const QString &text)
{
    loginMsg = text;
    u_homepage->getLoginMsg(text);
}

void Widget::sentMsg(double fee)
{
    //查询剩余车位
    QSqlQuery query;
        query.prepare("SELECT COUNT(*) FROM stall WHERE state = 0;");
        if (!query.exec()) {
            qDebug() << "Error: SQL query failed: " << query.lastError().text();
            return;
        }
        int count = -1;
        // 获取查询结果
        if (query.next()) {
            count = query.value(0).toInt();
            //qDebug() << "Number of stalls with state 0:" << count;
        }else{
            return;
        }
        // 将 double 类型的 fee 转换为整数类型（假设费用以分为单位）
        int feeInt = static_cast<int>(fee); // 如果费用是以元为单位，则乘以100转换成分


        // 将 count1 和 feeInt 转换为固定长度的3位十进制字符串
        QString countStr = QString("%1").arg(count, 3, 10, QChar('0')); // 固定3位
        QString feeStr = QString("%1").arg(feeInt, 3, 10, QChar('0'));   // 固定3位


        // 组合所有部分形成最终的字符串
        QString finalString = QString("A%1%2B").arg(countStr).arg(feeStr);

        // 通过 TCP 发送给服务端
        socket_send_data->write(finalString.toLatin1());

        // 打印调试信息
        qDebug() << "Send data:" << finalString;
}
/*发送信息测试
void Widget::sentMsgs()
{
     QString finalString = "AA030050BB";
    socket_send_data->write(finalString.toLatin1());

    // 打印调试信息
    qDebug() << "Sent cost data:" << finalString;
}
*/
void Widget::get_datas()
{
    char buf[1024];
    memset(buf,0,1024);
    socket_data->read(buf,1024);
    QString strData(buf);
    //flag 1 温度 2 湿度 3 烟雾浓度
    u_homepage->insert_infomation(flag,strData);

    flag++;
    if(flag == 3){
            flag = 0;
    }
}

void Widget::get_image(QImage image)
{
    u_homepage->show_image(image);
}

void Widget::socket_data_accept()
{
    socket_data->connectToHost("192.168.2.56",8888);
    if(!socket_data->waitForConnected(1000)){
        qDebug() << "连接失败<Get Data port: 8888 >：" << socket_data->errorString();
        return; // 连接失败时退出线程
    }
    socket_data->write("get_data");

    socket_send_data->connectToHost("192.168.2.56", 8884);
    if (! socket_send_data->waitForConnected(1000)) {
        qDebug() << "连接失败：<Send cost port:8884>" <<  socket_send_data->errorString();
        return; // 连接失败时退出线程
    }


}
void Widget::printf_msg(){
    qDebug() << "湿度：" << information.humidity << " " << "烟雾浓度：" << information.MQ_2 << " " << "湿度：" << information.temperature << endl;

}

void Widget::Car_Num(QString num){
    qDebug() << "num = " << num << endl;
    u_stallpage->insert_num(num);
}

void Widget::page_init()
{
    u_homepage = new homepage(this);
    u_userpage = new userpage(this);
    u_stallpage = new stallpage(this);
    u_carpage = new carpage(this);
    u_accespage = new accespage(this);

    ui->stackedWidget->addWidget( u_homepage );//0
    ui->stackedWidget->addWidget( u_userpage );//1
    ui->stackedWidget->addWidget( u_stallpage);//2
    ui->stackedWidget->addWidget( u_carpage );//3
    ui->stackedWidget->addWidget( u_accespage);//4

    ui->stackedWidget->setCurrentIndex(0);

}

void Widget::on_btn_home_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void Widget::on_btn_user_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void Widget::on_btn_stall_clicked()
{
    ui->stackedWidget->setCurrentIndex(2);
}

void Widget::on_btn_access_clicked()
{
    ui->stackedWidget->setCurrentIndex(4);
}

void Widget::on_btn_car_clicked()
{
    ui->stackedWidget->setCurrentIndex(3);
}
